package org.example.main.service.impl;

import org.apache.log4j.Logger;
import org.example.main.entity.Admin;
import org.example.main.dao.AdminMapper;
import org.example.main.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    private static final Logger logger = Logger.getLogger(AdminServiceImpl.class);

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public int add(Admin admin) {
        logger.info("Adding new admin with username: " + admin.getUsername());
        int result = adminMapper.insert(admin);
        logger.info("Admin added with ID: " + admin.getAdminId() + ", result: " + result);
        return result;
    }

    @Override
    public int deleteById(long adminId) {
        logger.info("Deleting admin by ID: " + adminId);
        int result = adminMapper.deleteById(adminId);
        logger.info("Admin deletion result: " + result);
        return result;
    }

    @Override
    public int updateById(Admin admin) {
        logger.info("Updating admin with ID: " + admin.getAdminId());
        int result = adminMapper.updateById(admin);
        logger.info("Admin update result: " + result);
        return result;
    }

    @Override
    public Admin findById(long adminId) {
        logger.info("Finding admin by ID: " + adminId);
        Admin admin = adminMapper.findById(adminId);
        logger.debug("Found admin: " + admin);
        return admin;
    }

    @Override
    public Admin findByUsername(String username) {
        logger.info("Finding admin by username: " + username);
        Admin admin = adminMapper.findByUsername(username);
        logger.debug("Found admin: " + admin);
        return admin;
    }

    @Override
    public List<Admin> findAll() {
        logger.info("Retrieving all admins");
        List<Admin> admins = adminMapper.findAll();
        logger.debug("Found " + admins.size() + " admins");
        return admins;
    }

    @Override
    public Map<String, Object> getAdminPage(int currentPage, int size) {
        logger.info("Getting admin page - currentPage: " + currentPage + ", size: " + size);
        //计算分页起始行的索引
        int start = (currentPage - 1) * size;
        //创建Map对象，用于储存储存分页的结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total",adminMapper.findAll().size());
        resultMap.put("record",adminMapper.getUserByPage(start,size));
        logger.debug("Page result - total: " + resultMap.get("total"));
        return resultMap;
    }
}
